package com.qf.qfgateway.filters;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.R;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;

@Component
@Order(-5) //控制过滤器执行优先级
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //解决中文乱码
        response.getHeaders().set("content-type","application/json;charset=utf-8");

        //资源放行
        URI uri = request.getURI();
        String path = uri.getPath();

        //判断是否是登录 or 注册相关的资源

        //判断是否登录
        String token = request.getQueryParams().getFirst("token");

        if (token != null && token.length() != 0){
            //对token进行认证
        }else{
            //不放行,提示用户尚未登录
            R r = R.error().putMsg("尚未登录");
            String rStr = JSON.toJSONString(r);

            //将我们的自定义数据包装成一个DataBuffer对象
            DataBuffer dataBuffer = response.bufferFactory().wrap(rStr.getBytes(StandardCharsets.UTF_8));
            Mono<DataBuffer> body = Mono.just(dataBuffer);

            return response.writeWith(body);
        }


        return chain.filter(exchange); //放行
    }
}
